#!/bin/bash
# MCP Unified Gateway Setup Script

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Configuration
MCP_HOME="${HOME}/.mcp"
GATEWAY_CONFIG_DIR="${MCP_HOME}/gateway"
CONFIG_FILE="${GATEWAY_CONFIG_DIR}/config.json"

echo -e "${BLUE}🚀 MCP Unified Gateway Setup${NC}"
echo "================================"

# Check prerequisites
check_prerequisites() {
    echo -e "\n${YELLOW}Checking prerequisites...${NC}"
    
    # Check Node.js
    if ! command -v node &> /dev/null; then
        echo -e "${RED}❌ Node.js is required but not installed.${NC}"
        echo "   Please install Node.js 18 or later: https://nodejs.org"
        exit 1
    fi
    
    NODE_VERSION=$(node -v | cut -d'v' -f2 | cut -d'.' -f1)
    if [ "$NODE_VERSION" -lt 18 ]; then
        echo -e "${RED}❌ Node.js 18 or later is required (found v${NODE_VERSION}).${NC}"
        exit 1
    fi
    
    echo -e "${GREEN}✅ Node.js $(node -v) found${NC}"
    
    # Check npm
    if ! command -v npm &> /dev/null; then
        echo -e "${RED}❌ npm is required but not installed.${NC}"
        exit 1
    fi
    
    echo -e "${GREEN}✅ npm $(npm -v) found${NC}"
}

# Create configuration directory
setup_directories() {
    echo -e "\n${YELLOW}Setting up directories...${NC}"
    
    mkdir -p "${GATEWAY_CONFIG_DIR}"
    mkdir -p "${MCP_HOME}/servers"
    mkdir -p "${MCP_HOME}/logs"
    
    echo -e "${GREEN}✅ Created configuration directories${NC}"
}

# Copy configuration templates
setup_config() {
    echo -e "\n${YELLOW}Setting up configuration...${NC}"
    
    # Copy environment template if .env doesn't exist
    if [ ! -f "${GATEWAY_CONFIG_DIR}/.env" ]; then
        if [ -f "templates/env-template" ]; then
            cp "templates/env-template" "${GATEWAY_CONFIG_DIR}/.env"
            echo -e "${GREEN}✅ Created .env file${NC}"
        fi
    else
        echo -e "${BLUE}ℹ️  .env file already exists${NC}"
    fi
    
    # Create default config if it doesn't exist
    if [ ! -f "${CONFIG_FILE}" ]; then
        cat > "${CONFIG_FILE}" <<EOF
{
  "gateway": {
    "port": 3000,
    "host": "localhost"
  },
  "discovery": {
    "enabled": true,
    "paths": [
      "~/.mcp/servers",
      "~/.local/share/mcp-servers"
    ]
  },
  "servers": {},
  "logging": {
    "level": "info",
    "pretty": true
  }
}
EOF
        echo -e "${GREEN}✅ Created default configuration${NC}"
    else
        echo -e "${BLUE}ℹ️  Configuration file already exists${NC}"
    fi
}

# Discover installed MCP servers
discover_servers() {
    echo -e "\n${YELLOW}Discovering MCP servers...${NC}"
    
    # Run discovery script if available
    if [ -f "scripts/discover-servers.js" ]; then
        node scripts/discover-servers.js
    else
        echo -e "${YELLOW}⚠️  Discovery script not found, skipping auto-discovery${NC}"
    fi
}

# Install recommended servers
install_servers() {
    echo -e "\n${YELLOW}Recommended MCP servers:${NC}"
    echo "  • filesystem - File operations"
    echo "  • shell - Command execution"
    echo "  • git - Version control"
    
    read -p "Would you like to install recommended servers? (y/n) " -n 1 -r
    echo
    
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        echo -e "\n${YELLOW}Installing MCP servers...${NC}"
        
        # Check if servers are available via npm
        if npm view @modelcontextprotocol/server-filesystem &> /dev/null; then
            npm install -g @modelcontextprotocol/server-filesystem
            echo -e "${GREEN}✅ Installed filesystem server${NC}"
        fi
        
        # Add more server installations as they become available
        echo -e "${BLUE}ℹ️  Additional servers can be installed later${NC}"
    fi
}

# Create systemd service (Linux only)
setup_service() {
    if [[ "$OSTYPE" == "linux-gnu"* ]]; then
        echo -e "\n${YELLOW}Would you like to install as a systemd service? (y/n)${NC}"
        read -p "" -n 1 -r
        echo
        
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            # Create service file
            sudo tee /etc/systemd/system/mcp-gateway.service > /dev/null <<EOF
[Unit]
Description=MCP Unified Gateway
After=network.target

[Service]
Type=simple
User=$USER
WorkingDirectory=$PWD
ExecStart=$(which node) $PWD/dist/index.js
Restart=on-failure
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF
            
            sudo systemctl daemon-reload
            echo -e "${GREEN}✅ Systemd service installed${NC}"
            echo -e "${BLUE}ℹ️  Start with: sudo systemctl start mcp-gateway${NC}"
        fi
    fi
}

# Final instructions
show_completion() {
    echo -e "\n${GREEN}✅ Setup complete!${NC}"
    echo -e "\n${YELLOW}Next steps:${NC}"
    echo "1. Review configuration at: ${CONFIG_FILE}"
    echo "2. Set any required environment variables in: ${GATEWAY_CONFIG_DIR}/.env"
    echo "3. Start the gateway:"
    echo "   npm start"
    echo ""
    echo "For more information, see the documentation:"
    echo "   https://github.com/devops/mcp-unified-gateway"
}

# Main setup flow
main() {
    check_prerequisites
    setup_directories
    setup_config
    discover_servers
    install_servers
    setup_service
    show_completion
}

# Run main function
main